package cn.edu.hziee;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BuyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if (id == null){
            response.sendRedirect("/ShoppingCart/Shopping.jsp");
            return;
        }
        HttpSession session = request.getSession();
        Production production = ProductionDB.getProduction(id);

        List<Production> cart = (List) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<Production>();
            session.setAttribute("cart",cart);
        }

 a:       if(cart.size()!=0){
            for(int i =0; i<cart.size();i++){
                if(production.getId()==cart.get(i).getId()){
                    cart.get(i).setNumber( cart.get(i).getNumber()+1);
                    break a;
                }
            }
            cart.add(production);
        }else{
            cart.add(production);
        }
        response.sendRedirect("/ShoppingCart/Shopping.jsp");
    }
}
